package ren.steve.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import ren.steve.common.result.HttpStatus;
import ren.steve.common.result.Result;
import ren.steve.common.utils.JwtHelper;
import ren.steve.common.utils.MD5;
import ren.steve.model.system.bean.SystemUser;
import ren.steve.model.system.vo.LoginVo;
import ren.steve.system.exception.CustomException;
import ren.steve.system.service.LoginService;
import ren.steve.system.service.SystemUserRoleService;
import ren.steve.system.service.SystemUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description:
 * @Date: Created in 2024/1/30 14:14
 */

@Api(tags = "APIs-登录")
@CrossOrigin
@RestController
@RequestMapping("/api/admin")
public class IndexController {

  @Autowired
  private LoginService loginService;

  @Autowired
  private SystemUserService systemUserService;

  @Autowired
  private SystemUserRoleService systemUserRoleService;

  @ApiOperation("API-登录")
  @PostMapping("/login")
  public Result login (@RequestBody LoginVo vo) {
    SystemUser user = loginService.login(vo);

    if (user == null) {
      throw new CustomException(HttpStatus.NOT_USER_EXIST.getCode(), HttpStatus.NOT_USER_EXIST.getMessage());
    }
    // 判断用户密码是否正确
    String password = vo.getPassword();
    String md5Password = MD5.encrypt(password);
    if (!user.getPassword().equals(md5Password)) {
      throw new CustomException(HttpStatus.PASSWORD_ERROR.getCode(), HttpStatus.PASSWORD_ERROR.getMessage());
    }
    // 判断用户是否可用 status != 999
    if (user.getStatus().equals("999")) {
      throw new CustomException(HttpStatus.ACCOUNT_STOP.getCode(), HttpStatus.ACCOUNT_STOP.getMessage());
    }

    String token = JwtHelper.createToken(user.getId(), user.getCode(),user.getEmail(), user.getPhone());
    Map<String, Object> map = new HashMap<>();
    map.put("token", token);
    map.put("id", user.getId());
    map.put("code", user.getCode());
    map.put("email", user.getEmail());
    map.put("phone", user.getPhone());
    map.put("name", user.getName());
    map.put("nickname", user.getNickname());
    map.put("avatar", user.getAvatar());
    return Result.ok(map, HttpStatus.OK);
  }

  @PreAuthorize("hasAuthority('/api/admin/info')")
  @ApiOperation("API-获取用户详情")
  @GetMapping("info")
  public Result info(HttpServletRequest request) {
    //获取请求头token字符串
    String token = request.getHeader("token");

    //从token字符串获取用户名称（id）
    String userId = JwtHelper.getUserId(token);
    //根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限数据）
    SystemUser user = systemUserService.getById(userId);
    user.setPassword(null);

    return Result.ok(user, HttpStatus.OK);
  }

}
